//
//  AppDelegate.m
//  Dispatch
//
//  Created by hyeyeon on 14. 1. 13..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "AppDelegate.h"
#import "PhotoViewController.h"

#define ENCRYPTKEY      @"1ae49a1a1eb120723f07f1260b145526"
#define DATAENCRYPTKEY  @"eltmvoclmezzomediadispatchmezzo!"

@implementation AppDelegate
@synthesize responseData, autoSearchArray, keywordsArray, iconsArray, notiContent, issueAdCount, starAdCount, currentLanguage, iconDictionary, receieveDic, mToken, battleAdCount, battleAdTime;

//크래쉬
void uncaughtExceptionHandler(NSException *exception) {
    NSLog(@"~~CRASH: %@", exception);
    NSLog(@"~~Stack Trace: %@", [exception callStackSymbols]);
    // Internal error reporting
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
     NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    
    //언어값
    self.currentLanguage = [self loadCurrentLanguage];
    
    //애널리틱스
    [self analyticsTracker];    
    
    //캐시메모리관리
    cacheMemory = [[CacheMemory alloc] init];
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    
    for (int i = 0; i<[path count]; i++) {
        NSArray *array = [cacheMemory.fileManager subpathsAtPath:[path objectAtIndex:i]];
        NSLog(@"이미지수 : %d",array.count);
        NSLog(@"<<<%@>>>\n%@",[path objectAtIndex:i],array);
    }
    
    NSString *udid = [self encryptString:[OpenUDID value]];

    
    //udid
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"]) {
        
        NSLog(@"기존것과 맞춤");
        [[NSUserDefaults standardUserDefaults] setObject:udid forKey:@"uuid"];
    }
    
    //noti
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound];
    
    UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    NSDictionary* userInfo          = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (localNotif)                 [self application:application didReceiveLocalNotification:localNotif];
	else if(userInfo != nil)        [self application:application didReceiveRemoteNotification:userInfo];
    
    
    self.responseData = [NSMutableData data];
    
    //일단 첫실행부터 보냄
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"devicetoken"];
    if (token) {
        [self sendlogData:0];
    }else{
        [self sendlogData:1];
    }
    
    //토큰받으면 보낼거임
//    NSString *url2=@"";
//    url2 = [NSString stringWithFormat:@"%@?os=ios&store=apple&deviceid=%@&key=%@&lang=%@",URL_REGEDIT,[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],@"devicetokensample",self.currentLanguage];
//    url2 = [url2 stringByReplacingOccurrencesOfString:@" " withString:@""];
//    [self requestURL:url2];
    
    //옛날에 본캐시지우기
    [cacheMemory removeCacheBefore:5];
    
    return YES;
}
							
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [FBAppEvents activateApp];
    [FBAppCall handleDidBecomeActive];

}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    [FBSession.activeSession close];
}

#pragma mark 노티
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    [UIApplication sharedApplication].applicationIconBadgeNumber=0;
    
    ViewController *root = (ViewController*)self.window.rootViewController;
    [root dismissViewControllerAnimated:NO completion:nil];
    
    if ([UIApplication sharedApplication].applicationState == 0) {
        //0이면 현재화면에 실행상태
        
        self.receieveDic = userInfo;
        NSString *msg = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
        
        [[PopupView getPopupViewWithDelegate:self] appearMessage:msg withFirstButton:NSLocalizedString(@"Ok",@"Ok") andSecondButton:NSLocalizedString(@"Cancel", @"Cancel") andTag:3];
    }else{
        //백그라운드에서 들어올때
        
        
        NSArray *notiar = [userInfo objectForKey:@"m"];
        NSString *notitype = [notiar objectAtIndex:0];  //i=issue, s=star, n=notice
        
        NSString *contentid = [NSString stringWithFormat:@"%d",[[notiar objectAtIndex:1] intValue]];
        NSString *pushid = [NSString stringWithFormat:@"%d",[[notiar objectAtIndex:2] intValue]];
        
        //코딩
        [self openPushType:notitype andContentID:contentid andPushID:pushid];
    }
    
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
	NSString *strDeviceToken = [[deviceToken description] stringByTrimmingCharactersInSet:
								[NSCharacterSet characterSetWithCharactersInString:@"&lt;&gt;"]];
	strDeviceToken = [strDeviceToken stringByReplacingOccurrencesOfString:@" " withString:@""];
	strDeviceToken = [[strDeviceToken substringFromIndex:1] substringToIndex:64];
    
	//devicetoken 저장
//	[[NSUserDefaults standardUserDefaults] setObject:strDeviceToken forKey:@"devicetoken"];
    NSLog(@"토큰 받음 : %@",strDeviceToken);
    self.mToken = strDeviceToken;
    
}


- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"토큰 가져오기 실패 : %@",error);
}

#pragma mark 스키마
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{

    NSString *photourl = url ? [NSString stringWithFormat:@"%@",url] : @"";
    NSLog(@"AppDelegate_url : %@",photourl);
    ViewController *root = (ViewController*)self.window.rootViewController;
    
    if ([photourl hasPrefix:@"dispatch://launch"]) {
        
        [root dismissViewControllerAnimated:NO completion:nil];
        
        NSInteger point = [photourl rangeOfString:@"pid="].location;
        if (point != NSNotFound) {
            NSArray *strArr = [photourl componentsSeparatedByString:@"pid="];

            
            if ([strArr count] > 1) {
                
                NSString *pidValue = [strArr objectAtIndex:1];
                
                
                if (pidValue.length > 0) {
                    //포토 아이디 존재
                    //pid = 포토이슈 아이디
                    //코딩
                    [root requestPhotoID:pidValue];
                }
            }
            
            
        }else{
            NSString *sidString = @"";
            NSString *cString = @"";
            NSArray *strArr = [photourl componentsSeparatedByString:@"?"];
            if ([strArr count] > 1) {
                
                photourl = [strArr objectAtIndex:1];
                strArr = [photourl componentsSeparatedByString:@"&"];
                //
                for (NSString *parameter in strArr) {
                    NSArray *tmpArr = [parameter componentsSeparatedByString:@"="];
                    
                    if ([tmpArr count] >= 2 ) {
                        
                        NSString *field = [tmpArr objectAtIndex:0];
                        NSString *value = [tmpArr objectAtIndex:1];
                        
                        
                        if ([field isEqualToString:@"sid"]) {
                            sidString = value;
                        }else{
                            cString = value;
                        }
                        
                    }
                    
                    //코딩
                }
                
                if (sidString.length > 0 || cString.length > 0) {
                    
                    
                    NSLog(@"sidString : %@ | cString : %@",sidString,cString);
                    [self openSchemeType:cString andID:sidString];
                    
                }
            }
        }
    }
    else if ([photourl hasPrefix:@"dispatch://goPage"]) {
        //dispatch://goPage_'타입'_'아이디'
        
        [root dismissViewControllerAnimated:NO completion:nil];

        
        NSLog(@"photo url : %@",photourl);
        NSArray *strArr = [photourl componentsSeparatedByString:@"_"];
        NSString *page = [strArr objectAtIndex:1];
        NSString *idStr = @"";
        if ([strArr count] >= 3) {
            
            idStr = [strArr objectAtIndex:2];
        }
        
        [self openSchemeType:page andID:idStr];
        
        ///코딩
//        [root clickMenu:위치번호]
//        [root apearPhotoControllerFromScheme:위치번호 andId:idStr];

        
    }
    else{
        //        스타 이벤트는 이거로 변경
        //    dispatch://launch?sid=<?=$i?>&c=<?=$t?>
        //http://dispatch.appvista.com/gw/?i=1234
        NSArray *parses = [photourl componentsSeparatedByString:@"?pid="];
        
        if ([parses count]>1) {
            NSString *photoid = [parses objectAtIndex:1];
            
            if (photoid.length > 0) {
                //포토 아이디 존재
                
                //코딩
            }else{
                NSLog(@"zzzzz");
            }
            
        }
    }
    
    
//    return [FBAppCall handleOpenURL:url
//                  sourceApplication:sourceApplication
//                    fallbackHandler:^(FBAppCall *call) {
//                        NSLog(@"In fallback handler");
//                    }];
    
    return [FBAppCall handleOpenURL:url
                  sourceApplication:sourceApplication
                    fallbackHandler:^(FBAppCall *call) {
                        NSLog(@"In fallback handler");
                    }];;
}

//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
//    return [[FBSession activeSession] handleOpenURL:url];
//    [FBAppCall handleDidBecomeActive];
//}


#pragma mark - 네트워크

-(void)getImgDownload:(NSString*)imgurl setImage:(id)image
{
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imgurl]];
    
    //이미지 뷰이면
    if ([image isKindOfClass:[UIImageView class]]) {
        __weak  UIImageView *_imgview = (UIImageView*)image;
        [_imgview setImageWithURLRequest:request placeholderImage:nil  success:^(NSURLRequest *request , NSHTTPURLResponse *response , UIImage *downimage ){
            
            _imgview.alpha=0.0f;
            [_imgview setImage:downimage];
            
            
            [UIView animateWithDuration:0.3f animations:^(void){
                _imgview.alpha=1.0f;
                
                ;}];
            
            
                //캐시저장
            
            
        }
                                 failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
                                     NSLog(@"failed loading: %@", error);
                                 }
         ];
    }
    else
    {
    }
    
    
}


-(void)getRequestTest:(NSString*)url
{
    
    
    
    // Do any additional setup after loading the view, typically from a nib.
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    
    
    
}


-(BOOL)connectedToNetwork
{
	// Create zero addy
	struct sockaddr_in zeroAddress;
	bzero(&zeroAddress, sizeof(zeroAddress));
	zeroAddress.sin_len = sizeof(zeroAddress);
	zeroAddress.sin_family = AF_INET;
	
	// Recover reachability flags
	SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
	
	SCNetworkReachabilityFlags flags;
	
	BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
	CFRelease(defaultRouteReachability);
	if (!didRetrieveFlags)
	{
		printf("Error. Could not recover network reachability flags\n");
		return 0;
	}
	
	BOOL isReachable = flags & kSCNetworkFlagsReachable;
	BOOL needsConnection = !(flags & kSCNetworkFlagsConnectionRequired);
	//	BOOL isEDGE = flags & kSCNetworkReachabilityFlagsIsWWAN;
	
	// WiFi는 연결이 되어 있으나 Internet 사용 불가 체크....shyoon
	if ((flags & kSCNetworkReachabilityFlagsIsDirect))
	{
		needsConnection = NO;
	}
	
	return (isReachable && needsConnection) ? YES : NO;
}

-(BOOL)checkObject:(id)object{
    
    if (object) {
        if (![object isKindOfClass:[NSNull class]]) {
            return YES;
        }
    }
    return NO;
}

#pragma mark 요청

//1. 실행로그
-(void)sendlogData:(int)first
{
    
    NSLog(@"요청! 실행로그 : %d",first);
    NSString *uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"];
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *appBuildVer = [infoDict objectForKey:@"CFBundleVersion"];
    NSString *url=@"";
    
    NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
    
    url = [NSString stringWithFormat:@"%@?p=ios&d=%@&av=%@&n=%@&t=1&e=%d",URL_EXEC,uuid,appBuildVer,language,first];
    url = [url stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    [self requestURL:url];
    
    
}

//2.초기데이타
-(void)requestInit{
    
    NSLog(@"요청! 초기데이터(init.php)");
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSDate *date = [NSDate date];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    NSString *dateStr = [dateFormatter stringFromDate:date];
    //    int timestamp = [[NSDate date] timeIntervalSince1970];
    
    NSString *dataString = [NSString stringWithFormat:@"timestamp=%@&os=ios&lang=%@&store=apple&deviceid=%@",dateStr,self.currentLanguage,[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"]];
    
    
    dataString = [self encryptDataURLString:dataString];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@", URL_INIT,dataString];      //암호화
    
    [self requestURL:url];
    
    //    [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(aesTest) userInfo:Nil repeats:NO];    //암호화 테스트
    
}

//3. 레지스터
-(void)requestRegisterWithTokenValue:(NSString*)token{

    NSLog(@"요청! register");
    NSString *string = [NSString stringWithFormat:@"os=ios&store=apple&deviceid=%@&key=%@&lang=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],token,self.currentLanguage];
    string = [self encryptDataURLString:string];
    
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_REGISTER,string];
    [self requestURL:url];
}

//임시 : 암호화 테스트
-(void)aesTest{
    
    NSString *did = [[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"];
    NSString *type = @"ty";
    NSString *str = @"str";
    NSString *par = [NSString stringWithFormat:@"did=%@&type=%@&str=%@",did,type,str];
    
    
    NSString *data = [self encryptDataURLString:par];
    NSString *url = [NSString stringWithFormat:@"http://devdispatchapi.mapps.kr/v5/aes_test.php?p=%@",data];
    [self requestURL:url];
}

-(void)requestURL:(NSString*)url{
    if ([self connectedToNetwork]) {
        
        [self performSelectorOnMainThread:@selector(startRequestWithURL:) withObject:url waitUntilDone:NO];
    }else{
        NSLog(@"인터넷 연결 안됨");
        NSString *string = NSLocalizedString(@"Failed to load", @"");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:string delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
        [alert show];
    }
}

-(void)startRequestWithURL:(NSString*)url{
    @autoreleasepool {
        
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
            [request setHTTPMethod:@"POST"];
            
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            if(connection){
                NSLog(@"네트워크 요청 : %@",url);
            }
            
        }
    }
}

#pragma mark delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connectio{
    
    
    
    [self removeActivity];
    NSError *myError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    
    NSLog(@"connectio.currentRequest >>> %@",resultDictionary);
    NSString *currentRequestString = [NSString stringWithFormat:@"%@",connectio.currentRequest];
    
    if ([currentRequestString rangeOfString:URL_REGISTER].location != NSNotFound) {
        
        [[NSUserDefaults standardUserDefaults] setObject:self.mToken forKey:@"devicetoken"];
        
        return;
    }else if ([currentRequestString rangeOfString:@"log_exec.php"].location != NSNotFound){
        
        //실행로그 보내고 나서 초기데이타 부름
        [self requestInit];
        return;
    }
    
    
    
    
    if ([resultDictionary objectForKey:@"return_code"]) {
        if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0) {
            //데이타 제대로 넘어옴
            
            resultDictionary = [resultDictionary objectForKey:@"data"];
            
            //랭킹데이터
            self.keywordsArray = ([self checkObject:[resultDictionary objectForKey:@"keywords"]]) ? [resultDictionary objectForKey:@"keywords"]:nil;
            
            //자동검색어
            self.autoSearchArray = ([self checkObject:[resultDictionary objectForKey:@"auto_search"]]) ? [resultDictionary objectForKey:@"auto_search"] : nil;
            
            //리본아이콘정보 code:아이콘코드, codename:구분명, imgurl:이미지url
            self.iconsArray = ([self checkObject:[resultDictionary objectForKey:@"icons"]]) ? [resultDictionary objectForKey:@"icons"] : nil;
            if (self.iconsArray) {
                
                [self iconDictionarySetting:self.iconsArray];
            }
            
            //최신버전
            NSString *version = ([self checkObject:[resultDictionary objectForKey:@"version"]]) ? [resultDictionary objectForKey:@"version"] : nil;
            
            //0:공지사항없음, 1:팝업, 2:레이어팜업
            notiType = ([self checkObject:[resultDictionary objectForKey:@"noti_type"]]) ? [[resultDictionary objectForKey:@"noti_type"] integerValue] : 0;
            
            //팝업링크 1:이슈, 2:스타, 3:베스트컷(삭제됨), 4:공지
            notiSubType = ([self checkObject:[resultDictionary objectForKey:@"noti_sub_type"]]) ? [[resultDictionary objectForKey:@"noti_sub_type"] integerValue] : 0;
            
            //전면광고 노출여부 1:전면광고 띄움
            adFlag = ([self checkObject:[resultDictionary objectForKey:@"ad_flag"]]) ? [[resultDictionary objectForKey:@"ad_flag"] integerValue] : 0;
            
            //팝업타이틀 or 외부링크URL
            self.notiContent = ([self checkObject:[resultDictionary objectForKey:@"noti_content"]]) ? [resultDictionary objectForKey:@"noti_content"] : nil;
            
            //이슈 광고카운팅
            self.issueAdCount = ([self checkObject:[resultDictionary objectForKey:@"issue_ad_count"]]) ? [[resultDictionary objectForKey:@"issue_ad_count"] integerValue] : 10;
            
            //스타 광고카운팅
            self.starAdCount = ([self checkObject:[resultDictionary objectForKey:@"star_ad_count"]]) ? [[resultDictionary objectForKey:@"star_ad_count"] integerValue] : 10;
            
            //배틀 광고 카운팅
            self.battleAdCount = ([self checkObject:[resultDictionary objectForKey:@"battle_ad_count"]]) ? [[resultDictionary objectForKey:@"battle_ad_count"] integerValue] : 10;
            
            //배틀광고시간
            self.battleAdTime = ([self checkObject:[resultDictionary objectForKey:@"battle_ad_time"]]) ? [[resultDictionary objectForKey:@"battle_ad_time"] integerValue] : 3;
            
            NSDictionary *notiStatus = ([self checkObject:[resultDictionary objectForKey:@"noti_status"]]) ? [resultDictionary objectForKey:@"noti_status"] : nil;
            if (notiStatus) {
                
                if ([self checkObject:[notiStatus objectForKey:@"news"]]) {
                    BOOL news = [[notiStatus objectForKey:@"news"] boolValue];
                    [[NSUserDefaults standardUserDefaults] setBool:news forKey:UD_ALARM_NEWS];
                }
                if ([self checkObject:[notiStatus objectForKey:@"star"]]) {
                    BOOL news = [[notiStatus objectForKey:@"star"] boolValue];
                    [[NSUserDefaults standardUserDefaults] setBool:news forKey:UD_ALARM_STAR];
                }
                if ([self checkObject:[notiStatus objectForKey:@"battle"]]) {
                    BOOL news = [[notiStatus objectForKey:@"battle"] boolValue];
                    [[NSUserDefaults standardUserDefaults] setBool:news forKey:UD_ALARM_BATTLE];
                }
                if ([self checkObject:[notiStatus objectForKey:@"my"]]) {
                    BOOL news = [[notiStatus objectForKey:@"my"] boolValue];
                    [[NSUserDefaults standardUserDefaults] setBool:news forKey:UD_ALARM_MY];
                }
            }
            
            //버전체크
            if ([self checkLastVersion:version]) {
                //최신버전
                [self notiPopup];   //팝업창여부 확인하고 있으면 띄움
            }
            
            
            
            ViewController *viewController = (ViewController*)self.window.rootViewController;
            [viewController startRankingRolling];
            [viewController.titleView startRankingRolling];
            [viewController clickMenu:1]; //첫화면(임시)
            
            //초기데이타 부르고 나서 토큰값 디바이스아이디 보냄
            if (self.mToken) {
                [self requestRegisterWithTokenValue:self.mToken];
            }
        }
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"네트워크 요청 실패 : %@",error);
    [self removeActivity];
    NSString *string = NSLocalizedString(@"Failed to load", @"");
    [[PopupView getPopupViewWithDelegate:self] appearMessage:string withFirstButton:NSLocalizedString(@"Ok",@"Ok") andSecondButton:NSLocalizedString(@"Cancel",@"Cancel") andTag:4];
    
}

#pragma mark - 애널리틱스


-(void)analyticsTracker{
    // Optional: automatically send uncaught exceptions to Google Analytics.
    [GAI sharedInstance].trackUncaughtExceptions = YES;
    
    // Optional: set Google Analytics dispatch interval to e.g. 20 seconds.
    [GAI sharedInstance].dispatchInterval = 20;
    
    // Optional: set Logger to VERBOSE for debug information.
    [[[GAI sharedInstance] logger] setLogLevel:kGAILogLevelVerbose];
    
    // Initialize tracker.
    id<GAITracker> tracker = [[GAI sharedInstance] trackerWithTrackingId:analyticsKey];
    //tracker = [[GAI sharedInstance] defaultTracker]
}

-(void)analyticsScreen{
    
    
    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
    [tracker set:kGAIScreenName value:@"Home Screen"];
    [tracker send:[[GAIDictionaryBuilder createAppView] build]];
}

-(void)analyticsCategory:(NSString*)cate Action:(NSString*)act Label:(NSString*)label{
    
    NSLog(@"애널리틱스 쏨 : %@ | %@ | %@",cate,act,label);
    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
    [tracker send:[[GAIDictionaryBuilder createEventWithCategory:cate               // Event category (required)
                                                          action:act                // Event action (required)
                                                           label:label              // Event label
                                                           value:nil] build]];      // Event value
}


#pragma mark - 이미지
#pragma mark 부르기
- (void) loadAsyncImageFromURL:(NSURL *)url  imageBlock:(void (^) (UIImage *image))imageBlock errorBlock:(void(^)(void))errorBlock
{
    dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
                   {
                       NSData * data = [[NSData alloc] initWithContentsOfURL:url];
                       UIImage * image = [[UIImage alloc] initWithData:data];
                       if( image != nil )
                       {
                           imageBlock( image );
                       } else {
                           errorBlock();
                       }
//                       dispatch_async( dispatch_get_main_queue(), ^(void){
//                       });
                   });
}



- (void) loadAsyncImageFromDomain:(NSString *)domain andFileName:(NSString*)fileName imageBlock:(void (^) (UIImage *image))imageBlock errorBlock:(void(^)(void))errorBlock{
    
    //계속 부를 필요 없는 이미지 파악해서 처리해야함
    UIImage *resultImage = [cacheMemory findImage:fileName];
    if (resultImage) {
        //있기 땜에 바로 부름
        imageBlock(resultImage);
    }else{
        NSString *path = [domain stringByAppendingString:fileName];
        NSURL *url = [NSURL URLWithString:path];
        
        dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
                       {
                           NSData * data = [[NSData alloc] initWithContentsOfURL:url];
                           UIImage * image = [[UIImage alloc] initWithData:data];
                           
                           if( image != nil )
                           {
                               imageBlock( image );
                               [cacheMemory saveImage:UIImageJPEGRepresentation(image, 1.0f) andFileName:fileName];
                           } else {
                               errorBlock();
                           }
//                           dispatch_async( dispatch_get_main_queue(), ^(void){
//                               
//                           });
                       });
    }
    
}

- (void) loadAsyncImageFromURLString:(NSString *)urlString  imageBlock:(void (^) (UIImage *image))imageBlock errorBlock:(void(^)(void))errorBlock{
    NSString *tUrlString = [urlString stringByReplacingOccurrencesOfString:@"http://" withString:@""];
    
    UIImage *resultImage = [cacheMemory findImage:tUrlString];
    if (resultImage) {
        imageBlock(resultImage);
    }else{
        
        NSURL *url = [NSURL URLWithString:urlString];
        
        dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
                       {
                           NSData * data = [[NSData alloc] initWithContentsOfURL:url];
                           UIImage * image = [[UIImage alloc] initWithData:data];
                           if( image != nil )
                           {
                               imageBlock( image );
                               [cacheMemory saveImage:data andFileName:tUrlString];
                           } else {
                               errorBlock();
                           }
//                           dispatch_async( dispatch_get_main_queue(), ^(void){
//                           });
                       });
        
    }
    
}

#pragma mark 지우기
-(void)removeCacheMemory{
    [self analyticsCategory:ANA_CAT_CLICK Action:ANA_ACT_COMMON Label:ANA_LAB_C_Cashclean];
    [cacheMemory emptyCache];
}

#pragma mark - 팝업 딜리게이트
-(void)popupView:(PopupView *)popupView clickIndex:(NSInteger)index{
    
    if (popupView.tag == 1) {
        
        [self notiPopup];   //팝업창여부 확인하고 있으면 띄움
        //버전확인
        if (index == 0) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ituneURL]];
        }else{
            [self notiPopup];
        }
    }else if(popupView.tag == 2){
        if (index == 0) {
            //notiSubType ->1:이슈, 2:스타, 3:베스트컷(삭제됨), 4:공지
        }
    }else if (popupView.tag == 3){
        if (index == 0) {
            //켜있는 상태에서 노티들어옴/보겠다함
            [self settingNotificationDictionary:self.receieveDic];
        }
    }else if(popupView.tag == 4){
        if (index == 0) {
            
            [self appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5f)];
            [self requestInit];
        }else{
            
            exit(1);
        }
    }
}


#pragma mark - 스키마(노티)

-(void)openSchemeType:(NSString*)type andID:(NSString*)strID{
    
    ViewController *root = (ViewController*)self.window.rootViewController;
    if ([type isEqualToString:@"i"]) {
        //issue
        [root clickMenu:1];
        [root.issueView appearPhotoViewControllerWithID:strID];
        
    }else if([type isEqualToString:@"s"]){
        //스타랭킹
        [root clickMenu:5];
        [root appearStarListToID:strID];
        
    }else if([type isEqualToString:@"b"]){
        //battle
        [root clickMenu:2];
        
    }else if([type isEqualToString:@"n"]){
        //notice
        [root clickMenu:4];
        [root.myView settingButtonAction:nil];
        [root.myView appearNoticeView];
    }
}

-(void)openPushType:(NSString*)type andContentID:(NSString*)contentID andPushID:(NSString*)pushID{
    
    ViewController *root = (ViewController*)self.window.rootViewController;
    if ([type isEqualToString:@"i"]) {
        //속보
        [root clickMenu:1];
        [root.issueView appearPhotoViewControllerWithID:contentID andPushID:pushID];
    }else if ([type isEqualToString:@"s"]){
        //팔뤄스타속보
        [root clickMenu:5];
        [root appearStarListToID:contentID andPushID:pushID];
    }else if ([type isEqualToString:@"n"]){
        //공지
        [root clickMenu:4];
        [root.myView appearNoticeView];
    }else if ([type isEqualToString:@"b"]){
        //배틀
        [root clickMenu:2];
    }
}


-(void)settingNotificationDictionary:(NSDictionary*)dictionary{
    
    
    NSArray *notiar = [dictionary objectForKey:@"m"];
    NSString *notitype = [notiar objectAtIndex:0];
    NSString *contentid = [NSString stringWithFormat:@"%d",[[notiar objectAtIndex:1] intValue]];
    NSString *pushid = [NSString stringWithFormat:@"%d",[[notiar objectAtIndex:2] intValue]];
    
    [self openPushType:notitype andContentID:contentid andPushID:pushid];
    
}

#pragma mark - 미디어타입
-(NSString *)setMediaType:(NSString *)string{
    
    if ([string isEqualToString:@"T"]) {
        return NSLocalizedString(@"TV Report", @"");
    }else if([string isEqualToString:@"Z"]){
        return NSLocalizedString(@"ZoomInSport", @"");
    }else{
        return @"Dispatch";
    }
}


#pragma mark - HTML인코딩

-(NSString*)stringByHTMLEncodingWithString:(NSString*)_string{
    
    NSMutableString *temp = [_string mutableCopy];
    
    [temp replaceOccurrencesOfString:@"&amp;"
                          withString:@"&"
                             options:0
                               range:NSMakeRange(0, [temp length])];
    [temp replaceOccurrencesOfString:@"&lt;"
                          withString:@"<"
                             options:0
                               range:NSMakeRange(0, [temp length])];
    [temp replaceOccurrencesOfString:@"&gt;"
                          withString:@">"
                             options:0
                               range:NSMakeRange(0, [temp length])];
    [temp replaceOccurrencesOfString:@"&quot;"
                          withString:@"\""
                             options:0
                               range:NSMakeRange(0, [temp length])];
    [temp replaceOccurrencesOfString:@"&nbsp;"
                          withString:@" "
                             options:0
                               range:NSMakeRange(0, [temp length])];
    
    return temp;
}

#pragma mark - 아이콘
-(void)iconDictionarySetting:(NSArray*)iconList{
    iconDictionary = [[NSMutableDictionary alloc] init];
    
    for (NSDictionary *dic in iconList) {
        NSString *key = [dic objectForKey:@"code"];
        NSString *object = [dic objectForKey:@"imgurl"];
        [iconDictionary setObject:object forKey:key];
    }
    
}

#pragma mark - 버전확인
-(BOOL)checkLastVersion:(NSString*)lastVersion{
    
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];    //현재 앱버전

    NSComparisonResult compareResult;
    compareResult = [currentVersion compare:lastVersion];
    if (compareResult == NSOrderedAscending) {
        //앱 업데이트 하라고 창뜸
        
        [[PopupView getPopupViewWithDelegate:self] appearMessage:NSLocalizedString(@"NewVersion", @"New version released. \nUpdate now?")  withFirstButton:NSLocalizedString(@"Ok",@"Ok") andSecondButton:NSLocalizedString(@"Cancel", @"Cancel") andTag:1];
        return NO;
    }else{
        return YES;
    }
}

#pragma mark - 노티팝업
-(void)notiPopup{
    if (notiType == 0) {
        [self appearInterstitial];  //전면광고 있는지 확인하고 띄움
    }
    else if (notiType == 1) {
        //팝업
        [[PopupView getPopupViewWithDelegate:self] appearMessage:self.notiContent withFirstButton:NSLocalizedString(@"Ok",@"Ok") andSecondButton:NSLocalizedString(@"Cancel", @"Cancel") andTag:2];
    }else if(notiType == 2){
        //레이어팝업
        [[LayerPUView getLayerPUViewWithDelegate:self] appearWebURL:self.notiContent];
    }
}

-(void)appearNetworkError{
    [self alertViewWithMessage:NSLocalizedString(@"Failed to load", @"") andTimeInterval:2.0f];
}

#pragma mark - 버튼없는 일반팝업
-(void)alertViewWithMessage:(NSString*)message andTimeInterval:(NSTimeInterval)time{
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alertView show];
    
    [NSTimer scheduledTimerWithTimeInterval:time target:self
                                   selector:@selector(removeAlertView:)
                                   userInfo:alertView repeats:NO];
}

-(void)removeAlertView:(NSTimer*)timer
{
    UIAlertView *backview = (UIAlertView *)[timer userInfo];
    [backview dismissWithClickedButtonIndex:0 animated:YES];

}

#pragma mark - 전면광고 띄우기
-(void)appearInterstitial{
    
    if (languagesKorean) {
        if (adFlag == 1) {
        
            ManInterstitial *manInterstitial = [ManInterstitial shareInstance];
            [manInterstitial applicationID:@"dispatch/dispatch/" adWindowID:@"interstitial"];
            [manInterstitial startInterstitial];
        }
    }else{
        //애드몹 전면광고
    }
}

#pragma mark - Activity
-(void)appearActivityOnPoint:(CGPoint)point{
    
    if (!activityBGView) {
        activityBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, mySize.width, mySize.height-64)];
        [self.window addSubview:activityBGView];
    }
    
    if (!activityView) {
        
        activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        [activityBGView addSubview:activityView];
    }
    
    activityView.center = CGPointMake(point.x, point.y-32);
    [activityView startAnimating];
}

-(void)removeActivity{
    
    if (activityBGView) {
        if ([activityBGView superview]) {
            
            if (activityView) {
                [activityView stopAnimating];
                if ([activityView superview]) {
                    [activityView removeFromSuperview];
                }
            }
            [activityBGView removeFromSuperview];
        }
        
    }
    
    activityView = nil;
    activityBGView = nil;
}

#pragma mark - 페이드아웃 효과
-(void)effectFaceoutTargetView:(UIView*)tView{
    return;
    if (tView) {
        
//        NSLog(@"tview : %@",tView);
        
        tView.alpha = 0.0f;
        [UIView animateWithDuration:1.0f animations:^{
            tView.alpha = 1.0f;
        }];
    }
}

#pragma mark - 언어
-(NSString*)loadCurrentLanguage{
    
    NSString * language = [[NSLocale preferredLanguages] objectAtIndex:0];
    
    if (language) {
        
        if ([language length] >= 2) {
            return [language substringToIndex:2];
        }
    }
    
    return @"ko";
    
    
}


#pragma mark 암호화

-(NSString*)encryptString:(NSString *)str{
    
    NSData *cipherData = [[str dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:ENCRYPTKEY];
    NSString *cipherString = [cipherData base64EncodedStringWithWrapWidth:0];
    return cipherString;
}

//복호화
-(NSString*)decryptString:(NSString*)str{
    NSData *cipherData = [str base64DecodedData];
    return [[NSString alloc] initWithData:[cipherData AES256DecryptWithKey:ENCRYPTKEY] encoding:NSUTF8StringEncoding];
}

-(NSString*)encryptDataURLString:(NSString*)str{
    
    NSLog(@"인크립트 : %@",str);
    
    str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSData *cipherData = [[str dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:DATAENCRYPTKEY];
//    NSString *cipherString = [cipherData base64EncodedStringWithWrapWidth:0];
    NSString *cipherString = [cipherData base64EncodedString];
    
    return cipherString;
}

-(NSString*)decryptDataURLString:(NSString*)str{
    
    NSData *cipherData = [str base64DecodedData];
    return [[NSString alloc] initWithData:[cipherData AES256DecryptWithKey:DATAENCRYPTKEY] encoding:NSUTF8StringEncoding];
}




@end
